package example4;

import java.lang.reflect.Method;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

public class CglibProxy implements MethodInterceptor {
	private Enhancer enhancer = new Enhancer();

	public Object getProxy(Class clazz) {
		// 设置需要创建子类的类
		enhancer.setSuperclass(clazz);
		enhancer.setCallback(this);
		// 通过字节码技术动态创建子类实例
		return enhancer.create();
	}

	@Override
	public Object intercept(Object proxy, Method method, Object[] args,
			MethodProxy methodProxy) throws Throwable {
		// 1 方法调用前处理逻辑
		System.out.println("before you do thing");
		// 2 方法调用
		try {
			methodProxy.invokeSuper(proxy, args);
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
			// XXX
		}
		// 3 方法调用后处理逻辑
		System.out.println("after you do thing");
		return null;
	}
}
